package com.moon.app;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.moon.R;
import com.moon.common.AbstractActivity;
import com.moon.constants.MoonConstants;
import com.moon.utils.HttpClientUtils;

/**
 * 用户反馈
 * 
 * @author paul
 * @date 2014年5月25日
 */
public class FeedbackActivity extends AbstractActivity {
    private static final String TAG               = FeedbackActivity.class.getSimpleName();

    // 正式地址
    private static final String POST_FEEDBACK_URL = "/mobile_user/feedback.do";

    private EditText            editContent;
    private BootstrapButton     btnFeedback;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.feedback);

        editContent = (EditText) findViewById(R.id.content);
        btnFeedback = (BootstrapButton) findViewById(R.id.btnFeedback);

        btnFeedback.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String content = editContent.getText().toString();
                if (StringUtils.isBlank(content)) {
                    Toast.makeText(getApplicationContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                new FeedbackTask().execute(content, String.valueOf(getUser().getId()));
            }
        });

    }

    private boolean saveViaHttp(String content, String userId) throws Exception {
        Context context = getApplicationContext();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(MoonConstants.FEEDBACK_CONTENT, content));
        params.add(new BasicNameValuePair(MoonConstants.FEEDBACK_USER_ID, userId));
        String appInfo = getAppInfo(context);
        params.add(new BasicNameValuePair(MoonConstants.FEEDBACK_APPINFO_KEY, appInfo));
        String sysInfo = getSysInfo(context);
        params.add(new BasicNameValuePair(MoonConstants.FEEDBACK_SYSINFO_KEY, sysInfo));
        String returnValue = HttpClientUtils.post(MoonConstants.MOON_DOMAIN + POST_FEEDBACK_URL,
                params);
        if (returnValue == null) {
            return false;
        }
        if (!returnValue.contains("true")) {
            return false;
        }
        return true;
    }

    private String getSysInfo(Context context) {
        StringBuffer buf = new StringBuffer();
        buf.append("VERSION[");
        buf.append("CODENAME: " + android.os.Build.VERSION.CODENAME);
        buf.append(", RELEASE: " + android.os.Build.VERSION.RELEASE);
        buf.append(", SDK: " + android.os.Build.VERSION.SDK);
        buf.append(", SDK_INT: " + android.os.Build.VERSION.SDK_INT);
        buf.append("] ");
        buf.append("HARDWARE[");
        buf.append("BRAND: " + android.os.Build.BRAND);
        buf.append(", DEVICE: " + android.os.Build.DEVICE);
        buf.append(", DISPLAY: " + android.os.Build.DISPLAY);
        buf.append(", PRODUCT: " + android.os.Build.PRODUCT);
        buf.append(", MODEL: " + android.os.Build.MODEL);
        buf.append(", MANUFACTURER: " + android.os.Build.MANUFACTURER);
        buf.append("]");
        return buf.toString();
    }

    private String getAppInfo(Context context) {
        return new StringBuffer().append(getString(R.string.app_name)).append("-")
                .append(getVersionName(context)).append("(").append(getVersionCode(context))
                .append(")").toString();
    }

    private class FeedbackTask extends AsyncTask<String, String, Boolean> {
        ProgressDialog pd;

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                return saveViaHttp(params[0], params[1]);
            } catch (Exception e) {
                // 提示用户网络异常
                String message = getString(R.string.network_error);
                Log.e(TAG, message, e);
                publishProgress(message);
                return false;
            }
        }

        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(FeedbackActivity.this);
            pd.setMessage(getText(R.string.wait_searching));
            pd.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    // 允许返回键撤销
                    FeedbackTask.this.cancel(true);
                }
            });
            pd.show();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Toast.makeText(getApplicationContext(), R.string.feedback_send_done,
                        Toast.LENGTH_LONG).show();
                finish();
            }else{
                Toast.makeText(getApplicationContext(), R.string.network_error,
                        Toast.LENGTH_LONG).show();
            }
            pd.dismiss();
        }

        @Override
        protected void onProgressUpdate(String... values) {
            if (values != null && values.length > 0) {
                // 网络异常
                Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 获取当前应用版本
     * 
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verCode;
    }

    /**
     * 获取当前应用版本名称
     * 
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
            return "1.0";
        }
    }
}
